<?
namespace Api\Model
{
	/** Login
	 * @desc: Users database access model 
	**/
	class Login extends \Api\Model\DB
	{
		/** in module config:
			'Privilages'=>array(
				'Level'=>1,  - type of user privilages
				'Strict'=>true, - does privilages should be strict (only strict not above
				privilages can be validate)
				'FailRedirect'=>'/error/404',
			),
		**/
		private $m_privilages = array();
		private $m_Session = null;
		
		public function __initLogin()
		{		  
			if(!\Api\Session::SessionExists() && !$this->m_config['SessionInit'])
            {                
				throw new \Exception('Session is turned off! Please check your module config');
			}	
			if(!array_key_exists('Privilages', $this->m_config))
				throw new \Exception('Unable to check privilages if `Privilages` const doesn\'t exists');
											
			$this->m_privilages = $this->m_config['Privilages'];
			$this->m_Session = new \Api\Session;
		}
		
        /**
         * Logout user
         */
        static public function Logout()
        {
            \Api\Session::set('PrivilageLevel','');
			\Api\Session::set('Username','');	
			\Api\Session::set('Validate',false);
            \Api\Session::set('CheckedPrivilages',false);                    
						
        }
        
		/**
		 * Check actual user privilages
         * @param Array of address parameters, redirecting bool value
		**/
        //TODO: Repair this
		public function CheckPrivilages(array $param,$redirect = true){													
			$privLevel = \Api\Session::get('PrivilageLevel');
    
		//	if($this->m_privilages['Strict']?$this->m_privilages['Level']==$privLevel:
		//		$this->m_privilages['Level'] >= $privLevel && $this->m_Session->Validate)
		//	{					             			     
				if(isset($param[0]) && $param[0]='logout'){
					$this->m_Session->PrivilageLevel = '';
					$this->m_Session->Username = '';	
					$this->m_Session->Validate = false;
                    $this->m_Session->CheckedPrivilages = false;                    
																	
				}else					
					return true;				
		//	}
			
		//	if(('FailRedirect',$this->m_privilages) 
        //        && $redirect) $this->Redirect();			
				
			return false;
		}
		/** ValidateUser
		 * @desc: Checking user in database, if true,
		 * sets sessions 
		**/
		public function ValidateUser( array $_UserData )
		{			
			if($this->m_Session->Validate) return 2;
			$this->m_Session->Validate = false;
            
			if(array_key_exists('Login',$_UserData) && array_key_exists('Pass', $_UserData)
			 && array_key_exists('Submit',$_UserData))
			{
				$_Q = $this->Query('SELECT * FROM `users` WHERE `username`=:username AND `password`=md5(:password)', array(
					':username'=>
						array($_UserData['Login'],\PDO::PARAM_STR), 
					':password'=>
						array($_UserData['Pass'],\PDO::PARAM_STR) ));
						
				if(count($_Q)==1)
				{					
					$this->m_Session->PrivilageLevel = $_Q[0]['privilages'];
					$this->m_Session->Username = $_Q[0]['username'];	
					$this->m_Session->Validate = true;
                    $this->m_Session->Last_log = $_Q[0]['log-date'];
                    $this->m_Session->UserId = $_Q[0]['id'];
                    
                    // TODO: Fix it !
                    $this->Query('UPDATE `users` SET `log-date`=curdate() WHERE `username`="'.$_Q[0]['username'].'"');
					return 2;
				}	
				return 1;
			}
			return 0;
		}
		
		/**
         * Return username from current session
         * @static
         * @return string or false
         */
        static public function GetUsername(){
            return \Api\Session::get('Username');
        }
        
        static public function GetUserId(){
            return \Api\Session::get('UserId');
        }
        
        /**
         * Return privilage level from current session
         * @static
         * @return string or false
         */
        static public function GetPrivilages()
        {
            return \Api\Session::get('PrivilageLevel');
        }
        
        /**
         * Fast check if user is validated
         * @static
         * @return string or false
         */
        static public function IsValid()
        {
            return \Api\Session::get('Validate');
        }
        
        /**
         * Redirecting to url from FatalRedirect
         */ 
        public function Redirect()
        {
            header('Location: http://'.$_SERVER['HTTP_HOST'].$this->m_privilages['FailRedirect']);
        }
		 
         
         /**
          * Change username
          */
        public function ChangeUsername($new, $uid)
        {
            if($this->IsValid())
            {
                $Q = $this->Query('SELECT COUNT(`id`) as num FROM `users` WHERE `username`=:name',
                    array(':name'=>array($new,\PDO::PARAM_STR)));
                if($Q[0]['num'] == 0)
                {
                    $Q = $this->Query('UPDATE `users` SET `username`=:name WHERE `id`=:uid',
                        array(':name'=>array($new,\PDO::PARAM_STR),
                        ':uid'=>array($uid,\PDO::PARAM_INT)));
                    return true;
                }                
            }
            return false;
        }
        
        public function ChangePass($new, $old, $uid)
        {            
            $Q=$this->Query('SELECT COUNT(`id`) as `num` FROM `users` WHERE `password`=md5(:pass) AND `id`=:uid',
                 array(':pass'=>array($old, \PDO::PARAM_STR),
                    ':uid'=>array($uid,\PDO::PARAM_INT)));
            if($Q[0]['num'] == 1)
            {
                $Q = $this->Query('UPDATE `users` SET `password`=md5(:pass) WHERE `id`=:uid',
                    array(':pass'=>array($new, \PDO::PARAM_STR),
                    ':uid'=>array($uid,\PDO::PARAM_INT)));
                    
                return true;
            }
            return false;
        }
	};
}
?>